import store from "./store";
import Vue from "vue";

//为和pc端一致，模拟axios出口
const axios = {
	post: changeUniRequestToAxios.bind(this, "POST"),
	get: changeUniRequestToAxios.bind(this, "GET"),
	put: changeUniRequestToAxios.bind(this, "PUT"),
	delete: changeUniRequestToAxios.bind(this, "DELETE"),
	patch: changeUniRequestToAxios.bind(this, "PATCH"),
}

let requestTaskList = [];

function changeUniRequestToAxios(method, url, param = {}, showLoading = true) {
	return new Promise((resolve, reject) => {
		let header = {
			"Content-Type": "application/json",
		}
		if (store.state.session.token) { //设置token
			header["Authorization"] = store.state.session.token;
		}

		// #ifdef APP-PLUS
		header["VersionCode"] = store.state.version.wgt_versionCode;
		// #endif

		if (method == "GET" && param.params) { //模仿axios的get
			//防止小程序在query中拼接null
			for (var key in param.params) {
				if (param.params[key] == null) {
					param.params[key] = "";
				}
			}
			param = param.params;
		}

		let requestTask;
		let request = {
			url: store.state.appConfig.baseURL + url,
			data: param,
			header: header,
			method: method,
			success: (res) => {
				if (res.statusCode == 200 && res.data.code == 200) {
					resolve(res.data.data)
				} else {
					let errCode, errMsg;
					if (res.statusCode == 200) { //后端人工报错
						errCode = res.data.code;
						errMsg = res.data.message;
					} else { //系统报错
						console.log("request res", res)
						errCode = res.statusCode;
						errMsg = res.data.error.message;
					}
					
					
					if (errCode == 401) {
						//取消其他执行中的接口
						requestTaskList.forEach(task => task.abort());
						requestTaskList.splice(0);
						//注销
						store.commit("logout");
					} else if (errCode == 506) {
						//取消其他执行中的接口
						requestTaskList.forEach(task => task.abort());
						requestTaskList.splice(0);
						uni.showModal({
							content: '已检测到新版本，即将自动更新',
							showCancel: false,
							success: (res) => {
								plus.runtime.restart();
							}
						});
					} else {
						uni.showToast({
							title: errMsg,
							icon: 'none',
							duration: 3000
						});
					}
					reject(res.data)

				}
			},
			fail: (res) => {
				console.log("fail", res, res.errMsg)
				//非主动取消时显示请求发起失败
				if (res.errMsg != "request:fail abort") {
					uni.showToast({
						// title: "请求发起失败",
						title: "网络异常，请重试",
						icon: 'none',
						duration: 3000
					});
				}

				reject(res)
			},
			complete: () => {
				//去除已经完毕的请求
				var index = requestTaskList.indexOf(requestTask);
				if (index != -1) {
					requestTaskList.splice(index, 1);
				}
				if (!requestTaskList.length) {
					uni.stopPullDownRefresh();
					Vue.prototype.hideLoading()
				}

			}
		}
		//执行顺序 success=》complete=》then=》finally
		if (showLoading) {
			Vue.prototype.showLoading();
		}
		requestTask = uni.request(request);
		requestTaskList.push(requestTask);
	})

}


export default axios;